package com.web_bloks.http.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.web_bloks.system.client.Logger;

/**
 * 
 * @author Jean-Lou Dupont
 *
 */
public class JSONResponse {

	String code = null; 
	
	JSONObject obj = null;
	
	protected JSONResponse() {
	}
	
	public static JSONResponse fromJSONString(String response) {

		if (null==response)
			return null;
		
		JSONResponse resp = GWT.create(JSONResponse.class);
	
		JSONValue value = null;
		
		try {
			value = JSONParser.parse( response );
		} catch(JSONException e) {
			throw new RuntimeException("JSONResponse.fromJSONString: can't parse response data to JSON object");
		}
		
		if (null==value)
			return null;
		
		try {
			resp.obj = value.isObject();
			resp.code = resp.obj.get("code").isString().stringValue();
		} catch(Exception e) {
			resp.code = null;
			Logger.logWarn("JSONResponse.fromJSONString: error extracting parameters, msg="+e.getMessage());
		}
		
		return resp;
	}
	
	/**
	 * Verifies if the instance contains a specific field
	 * @param key
	 * @return
	 */
	public boolean contains(String key) {

		if (null==obj || null==key)
			return false;
		
		return obj.containsKey(key);
	}
	
	public String getString(String key) {
		return obj.get(key).isString().stringValue();
	}
}//END
